package com.strangebreeds.therefromhere;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import java.util.Random;
import java.lang.Math;

import com.strangebreeds.therefromhere.engine.*;

@MessageDriven(activationConfig = {
		@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
		@ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/tfh_job_q"),
		@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })
public class JobBean implements MessageListener
{
	private Logger logger = Logger.getLogger(JobBean.class);
	
	private Integer objectID;
	
	{
		Random random = new Random();
		objectID = Math.abs(random.nextInt());
		
		org.apache.log4j.PropertyConfigurator.configure("log4j.properties");
		logger.setLevel(Level.DEBUG);
	}
	
	public void onMessage(Message inMessage)
	{
		logger.debug("JobBean " + objectID + " got a new message");
		
		try
		{
			MapMessage msg = (MapMessage) inMessage;
			
			String fromPage = msg.getString("fromPage");
			String toPage = msg.getString("toPage");
			String searchStrategy = msg.getString("searchStrategy");
			String emailAddress = msg.getString("emailAddress");
			Integer jobID = msg.getInt("jobNumber");

			// Now we want to call the engine...
			logger.debug("JobBean " + objectID + " is creating the job object...");
			new WikiPageEngine(fromPage, toPage, searchStrategy, emailAddress, jobID);
		}
		catch (JMSException je)
		{
			logger.error("Hey, got a jmsexception of " + je.getMessage(), je);
		}
	}
}
